package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller//IOC注解，将Controller交给Spring容器管理
public class LoginController {

    @Autowired
    private IEmployeeService service;

    @Autowired
    private IPermissionService permissionService;

    //处理查询的请求
    @RequestMapping("/login")
    public String login(Model model, String username, String password, HttpSession session){

        try {
            Employee e = service.login(username, password);
            //没有异常，共享当前员工
            session.setAttribute("EMPLOYEE_IN_SESSION",e);


            //查询到当前用户拥有的所有权限表达式，使用session共享（供后面的检查使用）
            List<String> expressions = permissionService.getExpressionsByEmpId(e.getId());
            session.setAttribute("EXPRESSIONS_IN_SESSION",expressions);


            return "redirect:/employee/list.do";
        } catch (Exception e1) {
            e1.printStackTrace();


            //失败
            model.addAttribute("errorMsg", e1.getMessage());
            return "forward:/login.jsp";
        }
    }
}
